package com.example.fan.airline_reservation;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fan.airline_reservation.Model.Fight;
import com.example.fan.airline_reservation.Model.Order;
import com.example.fan.airline_reservation.Model.Passenger;
import com.example.fan.airline_reservation.Model.USER;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class traveler_bookticket extends AppCompatActivity {


    @BindView(R.id.FromBT)
    TextView FromBT;
    @BindView(R.id.ToBT)
    TextView ToBT;
    @BindView(R.id.flightNoBT)
    TextView flightNoBT;
    @BindView(R.id.Stime)
    TextView Stime;
    @BindView(R.id.Splace)
    TextView Splace;
    @BindView(R.id.flytimeBT)
    TextView flytimeBT;
    @BindView(R.id.Atime)
    TextView Atime;
    @BindView(R.id.Aplace)
    TextView Aplace;
    @BindView(R.id.Sdate)
    TextView Sdate;
    @BindView(R.id.priceBT)
    TextView priceBT;
    @BindView(R.id.PasNameBT)
    EditText PasNameBT;
    @BindView(R.id.IDNumBT)
    EditText IDNumBT;
    @BindView(R.id.telNumBT)
    EditText telNumBT;
    @BindView(R.id.checkBT)
    Button checkBT;
    @BindView(R.id.sexuality)
    EditText sexuality;
    @BindView(R.id.address)
    EditText address;

    /*封凡测试代码*/
    private LocalBroadcastManager localBroadcastManager;

    String price=new String();
    String sdate=new String();
    String flightNUM=new String();
    int sex=0;
    USER user;
    String Objectid_fight=new String();
    Order order;
    Date time;
    Passenger passenger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_traveler_bookticket);

        ButterKnife.bind(this);
        Bmob.initialize(traveler_bookticket.this, "0802cbf346296dc9fac5a477f911ba39");
        Intent intent = getIntent();
        String splace = intent.getStringExtra("splace");
        String aplece = intent.getStringExtra("aplace");
        String flytime = intent.getStringExtra("flytime");
        String stime = intent.getStringExtra("stime");
        String atime = intent.getStringExtra("atime");
        String Fromcity = intent.getStringExtra("FromCity");
        String Tocity = intent.getStringExtra("ToCity");
        time=new Date(intent.getLongExtra("time",0));
        flightNUM = intent.getStringExtra("flightNUM");
        price = intent.getStringExtra("price");
        sdate = intent.getStringExtra("sdate");
        Objectid_fight=intent.getStringExtra("objectid_fight");
        flightNoBT.setText(flightNUM);
        Stime.setText(stime);
        Atime.setText(atime);
        Splace.setText(splace);
        Aplace.setText(aplece);
        flytimeBT.setText(flytime);
        priceBT.setText(price + "¥");
        Sdate.setText(sdate);
        FromBT.setText(Fromcity);
        ToBT.setText(Tocity);
        user= (USER) getIntent().getSerializableExtra("USER11");
        checkBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (IDNumBT.getText().length()!=18||telNumBT.getText().length()!=11||PasNameBT.getText().length()==0
                        ||sexuality.getText().length()==0||address.getText().length()==0) {
                    if (IDNumBT.getText().length()!=18) {
                        ToastShow("请确认身份证信息");
                    }else if (telNumBT.getText().length()!=11){
                        ToastShow("请确认您的联系电话");
                    }else {
                        Toast.makeText(traveler_bookticket.this, "请检查您的乘机信息是否填写完整", Toast.LENGTH_SHORT).show();
                    }
                }

                else{
                    if(sexuality.getText().toString().equals("男")){
                        sex=0;
                        showdialog();
                    }
                    else if(sexuality.getText().toString().equals("女")){
                        sex=1;
                        showdialog();
                    }
                    else{
                        ToastShow("请确认您所输入的性别信息");
                    }
                }
            }
        });
    }

    private void showdialog(){
        Log.e("TestShowdialog","我没出错");
        AlertDialog.Builder builder=new AlertDialog.Builder(traveler_bookticket.this);
        double money=user.getMoney();
        builder.setMessage("是否购票？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
               dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                buyticket();
            }
        });
        builder.show();
    }
    private void buyticket()  {
        BmobQuery<USER> bmobQuery1=new BmobQuery<USER>();
        bmobQuery1.getObject(user.getObjectId(), new QueryListener<USER>() {
            @Override
            public void done(USER user1, BmobException e) {
                double money=user1.getMoney();
                double Price=Double.parseDouble(price);
                if(money<Price){
                    Toast.makeText(traveler_bookticket.this,"余额不足",Toast.LENGTH_LONG).show();
                }
                else{
                    BmobQuery<Fight> bmobQuery=new BmobQuery<Fight>();
                    bmobQuery.getObject(Objectid_fight, new QueryListener<Fight>() {
                        @Override
                        public void done(Fight fight, BmobException e) {
                            int temp=fight.getCurrentPeole()+1;
                            Fight f=new Fight(fight.getFLIGHT(),fight.getAIRCRAFT_MODEL(),fight.getDATE(),
                                    fight.getFROM(),fight.getFROMNAME(),fight.getTO(),fight.getTONAME(),fight.getPRICE(),
                                    fight.getTODATE(),fight.getCurrentPeole(),fight.getCurrentState(),fight.getDelayTime());
                            f.setCurrentPeole(temp);
                            f.update(Objectid_fight, new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if(e!=null){
                                        //Toast.makeText(traveler_bookticket.this,"ddd",Toast.LENGTH_SHORT).show();
                                        Toast.makeText(traveler_bookticket.this,e.getErrorCode()+"",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    });

                    passenger=new Passenger(PasNameBT.getText().toString(),sex,
                            address.getText().toString(),
                            IDNumBT.getText().toString(),telNumBT.getText().toString());
                    order=new Order(passenger,Price,time,flightNUM,user.getName());
                    order.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if(e==null){

                            }
                            else {
                                Toast.makeText(traveler_bookticket.this,"购票失败2",Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    String tempOB=user.getObjectId();
                    USER u=new USER(user.getName(),user.getPassword(),0);
                    u.setMoney(money-Price);
                    user.setMoney(money-Price);
                    u.update(tempOB, new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if(e==null){
                                Toast.makeText(traveler_bookticket.this,"购票成功",Toast.LENGTH_SHORT).show();
                                startLocalBroadcast();
                            }
                            else {
                                Toast.makeText(traveler_bookticket.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }
        });

    }

    private void startLocalBroadcast(){
        localBroadcastManager =LocalBroadcastManager.getInstance(this);
        Intent intent = new Intent("com.example.fan.airline_reservation.LOCAL");
        intent.putExtra("newInfo",user);
        localBroadcastManager.sendBroadcast(intent);
    }

    public void ToastShow(String message){
        Toast.makeText(traveler_bookticket.this,message,Toast.LENGTH_SHORT).show();
    }
}